#!/bin/bash
# cgreen-debug
#
# Script to start cgreen-runner under gdb, load a library and break
# on a named test.
#

# If you are viewing 'cgreen-debug' this *is* that script and you'll
# find the logic at the end of this file. To update it, edit
# `cgreen-debug.argbash` instead.

# But if you are looking at 'cgreen-debug.argbash' then this is
# actually a template for argbash (https://argbash.io) which generates
# argument parsing capable bash scripts from a template just like
# this.

# To generate a new 'cgreen-debug' use
#
#     'argbash cgreen-debug.argbash -o cgreen-debug'
#
# if you have argbash installed, or go to https://argbash.io and paste
# this file into the online version.

# ARG_HELP([Start cgreen-runner under GDB (or other debugger) and break at a specific test])
# ARG_OPTIONAL_SINGLE([debugger], d, [The debugger to use], [cgdb])
# ARG_POSITIONAL_SINGLE([library], [Dynamically loadable library with Cgreen tests], )
# ARG_POSITIONAL_SINGLE([testname], [The test to debug, in Cgreen notation ('<Context>:<test>')], )
# ARGBASH_GO

# [ <-- needed because of Argbash

if [ "$_arg_debugger" == "" ]; then
    if command -v cgdb > /dev/null 2>&1 ; then
        debugger=cgdb
    else
        debugger=gdb
    fi
else
    if command -v $_arg_debugger > /dev/null 2>&1 ; then
        debugger=$_arg_debugger
    else
        echo "No such debugger: $_arg_debugger"
        exit 1
    fi
fi

# Figure out where to place breakpoint by replacing ':' with '__'
bp=${_arg_testname//:/__}

if [ "$debugger" == "lldb" ] ; then
    echo break set -n $bp > .cgreen-debug-commands
    echo run $_arg_library $_arg_testname >> .cgreen-debug-commands
    $debugger cgreen-runner --source .cgreen-debug-commands
else
    echo break $bp > .cgreen-debug-commands
    echo run $_arg_library $_arg_testname >> .cgreen-debug-commands
    $debugger -ex "set breakpoint pending on" cgreen-runner --command=.cgreen-debug-commands
fi

rm .cgreen-debug-commands

# ] <-- needed because of Argbash
